/*
这是CSDN  _JT_  大神的代码，原创见
https://blog.csdn.net/weixin_42462202/article/details/99068041
*/

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <pthread.h>

#include "rtp.h"

#define H264_FILE_NAME   "test.h264"
#define SERVER_PORT     8554
#define SERVER_WEB_PORT  8000
#define SERVER_RTP_PORT  55532
#define SERVER_RTCP_PORT 55533
#define BUF_MAX_SIZE    (1024*1024)

#define RTSP_BUFFERSIZE 4096
#define MAX_DESCR_LENGTH 4096

typedef struct _RTP_transport
{
    int serverRtpSockfd;
	char clientIP[40];
	int clientRtpPort;	
} RTP_transport;

typedef struct _RTSP_buffer {
    int fd;    /*socketÎÄŒþÃèÊö·û*/
    unsigned int port;/*¶Ë¿ÚºÅ*/

    struct sockaddr stClientAddr;

    char in_buffer[RTSP_BUFFERSIZE];/*œÓÊÕ»º³åÇø*/
    unsigned int in_size;/*œÓÊÕ»º³åÇøµÄŽóÐ¡*/
    char out_buffer[RTSP_BUFFERSIZE+MAX_DESCR_LENGTH];/*·¢ËÍ»º³åÇø*/
    int out_size;/*·¢ËÍ»º³åÇøŽóÐ¡*/

    unsigned int rtsp_cseq;/*ÐòÁÐºÅ*/
    char descr[MAX_DESCR_LENGTH];/*ÃèÊö*/
    struct _RTSP_buffer *next; /*ÖžÏòÏÂÒ»žöœá¹¹Ìå£¬¹¹³ÉÁËÁŽ±íœá¹¹*/
    bool bufferisset;
    RTP_transport *prtptransport;
} RTSP_buffer;

bool rtpstatus = false;

static int createTcpSocket()
{
    int sockfd;
    int on = 1;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
        return -1;

    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));

    return sockfd;
}

static int createUdpSocket()
{
    int sockfd;
    int on = 1;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
        return -1;

    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));

    return sockfd;
}

unsigned int get_route_if_ip()
{

	int socket_fd;
	struct sockaddr_in *sin;
	struct ifreq *ifr;
	struct ifconf conf;
	char buff[BUFSIZ];
	int num;
	
	socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
	
	conf.ifc_len = BUFSIZ;
	conf.ifc_buf = buff;
	
	ioctl(socket_fd, SIOCGIFCONF, &conf);
	
	num = conf.ifc_len / sizeof(struct ifreq);
	ifr = conf.ifc_req;
	
	for (int i=0; i<num; i++)
	{
		struct sockaddr_in *sin = (struct sockaddr_in *)(&ifr->ifr_addr);

		ioctl(socket_fd, SIOCGIFFLAGS, ifr);
		if (((ifr->ifr_flags & IFF_LOOPBACK) == 0) && (ifr->ifr_flags & IFF_UP))
		{
			return sin->sin_addr.s_addr;
		}
		
		ifr++;
	}

	return 0;
}

static int bindSocketAddr(int sockfd, const char* ip, int port)
{
	struct sockaddr_in sin; 
	
	sin.sin_family = AF_INET; 
	sin.sin_port = htons(port);
	sin.sin_addr.s_addr = INADDR_ANY;
	if(bind(sockfd, (struct sockaddr *)&sin, sizeof(struct sockaddr)) < 0)
	    return -1;
	return 0;
}

static int acceptClient(int sockfd, char* ip, int* port)
{
    int clientfd;
    socklen_t len = 0;
    struct sockaddr_in addr;

    memset(&addr, 0, sizeof(addr));
    len = sizeof(addr);

    clientfd = accept(sockfd, (struct sockaddr *)&addr, &len);
    if(clientfd < 0)
        return -1;
    
    strcpy(ip, inet_ntoa(addr.sin_addr));
    *port = ntohs(addr.sin_port);

    return clientfd;
}

static char* getLineFromBuf(char* buf, char* line)
{
    while(*buf != '\n')
    {
        *line = *buf;
        line++;
        buf++;
    }

    *line = '\n';
    ++line;
    *line = '\0';

    ++buf;
    return buf; 
}

static inline int startCode3(char* buf)
{
    if(buf[0] == 0 && buf[1] == 0 && buf[2] == 1)
        return 1;
    else
        return 0;
}

static inline int startCode4(char* buf)
{
    if(buf[0] == 0 && buf[1] == 0 && buf[2] == 0 && buf[3] == 1)
        return 1;
    else
        return 0;
}

static char* findNextStartCode(char* buf, int len)
{
    int i;

    if(len < 3)
        return NULL;

    for(i = 0; i < len-3; ++i)
    {
        if(startCode3(buf) || startCode4(buf))
            return buf;
        
        ++buf;
    }

    if(startCode3(buf))
        return buf;

    return NULL;
}

static int getFrameFromH264File(int fd, char* frame, int size)
{
    int rSize, frameSize;
    char* nextStartCode;

    if(fd < 0)
        return fd;

    rSize = read(fd, frame, size);
    if(!startCode3(frame) && !startCode4(frame))
        return -1;
    
    nextStartCode = findNextStartCode(frame+3, rSize-3);
    if(!nextStartCode)
    {
        lseek(fd, 0, SEEK_SET);
        frameSize = rSize;
        //return -1;
    }
    else
    {
        frameSize = (nextStartCode-frame);
        lseek(fd, frameSize-rSize, SEEK_CUR);
    }

    //printf("get frame size %d\n", frameSize);
    return frameSize;
}

static int rtpSendH264Frame(int socket, const char* ip, int16_t port,
                            struct RtpPacket* rtpPacket, uint8_t* frame, uint32_t frameSize)
{
    uint8_t naluType; // nalu第一个字节
    int sendBytes = 0;
    int ret;

    naluType = frame[0];

    if (frameSize <= RTP_MAX_PKT_SIZE) // nalu长度小于最大包场：单一NALU单元模式
    {
        /*
         *   0 1 2 3 4 5 6 7 8 9
         *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         *  |F|NRI|  Type   | a single NAL unit ... |
         *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         */
        memcpy(rtpPacket->payload, frame, frameSize);
        ret = rtpSendPacket(socket, ip, port, rtpPacket, frameSize);
        if(ret < 0)
            return -1;

        rtpPacket->rtpHeader.seq++;
        sendBytes += ret;
        if ((naluType & 0x1F) == 7 || (naluType & 0x1F) == 8) // 如果是SPS、PPS就不需要加时间戳
            goto out;
    }
    else // nalu长度小于最大包场：分片模式
    {
        /*
         *  0                   1                   2
         *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3
         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         * | FU indicator  |   FU header   |   FU payload   ...  |
         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         */

        /*
         *     FU Indicator
         *    0 1 2 3 4 5 6 7
         *   +-+-+-+-+-+-+-+-+
         *   |F|NRI|  Type   |
         *   +---------------+
         */

        /*
         *      FU Header
         *    0 1 2 3 4 5 6 7
         *   +-+-+-+-+-+-+-+-+
         *   |S|E|R|  Type   |
         *   +---------------+
         */

        int pktNum = frameSize / RTP_MAX_PKT_SIZE;       // 有几个完整的包
        int remainPktSize = frameSize % RTP_MAX_PKT_SIZE; // 剩余不完整包的大小
        int i, pos = 1;

        /* 发送完整的包 */
        for (i = 0; i < pktNum; i++)
        {
            rtpPacket->payload[0] = (naluType & 0x60) | 28;
            rtpPacket->payload[1] = naluType & 0x1F;
            
            if (i == 0) //第一包数据
                rtpPacket->payload[1] |= 0x80; // start
            else if (remainPktSize == 0 && i == pktNum - 1) //最后一包数据
                rtpPacket->payload[1] |= 0x40; // end

            memcpy(rtpPacket->payload+2, frame+pos, RTP_MAX_PKT_SIZE);
            ret = rtpSendPacket(socket, ip, port, rtpPacket, RTP_MAX_PKT_SIZE+2);
            if(ret < 0)
                return -1;

            rtpPacket->rtpHeader.seq++;
            sendBytes += ret;
            pos += RTP_MAX_PKT_SIZE;
        }

        /* 发送剩余的数据 */
        if (remainPktSize > 0)
        {
            rtpPacket->payload[0] = (naluType & 0x60) | 28;
            rtpPacket->payload[1] = naluType & 0x1F;
            rtpPacket->payload[1] |= 0x40; //end

            memcpy(rtpPacket->payload+2, frame+pos, remainPktSize+2);
            ret = rtpSendPacket(socket, ip, port, rtpPacket, remainPktSize+2);
            if(ret < 0)
                return -1;

            rtpPacket->rtpHeader.seq++;
            sendBytes += ret;
        }
    }

out:

    return sendBytes;
}

static int tcp_rtpSendH264Frame(int socket, int rtpChannel, struct RtpPacket* rtpPacket, uint8_t* frame, uint32_t frameSize)
{
    uint8_t naluType; // nalu第一个字节
    int sendBytes = 0;
    int ret;

    naluType = frame[0];

    if (frameSize <= RTP_MAX_PKT_SIZE) // nalu长度小于最大包场：单一NALU单元模式
    {
        /*
         *   0 1 2 3 4 5 6 7 8 9
         *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         *  |F|NRI|  Type   | a single NAL unit ... |
         *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         */
        memcpy(rtpPacket->payload, frame, frameSize);
        ret = tcp_rtpSendPacket(socket, rtpChannel, rtpPacket, frameSize);
        if(ret < 0)
            return -1;

        rtpPacket->rtpHeader.seq++;
        sendBytes += ret;
        if ((naluType & 0x1F) == 7 || (naluType & 0x1F) == 8) // 如果是SPS、PPS就不需要加时间戳
            goto out;
    }
    else // nalu长度小于最大包场：分片模式
    {
        /*
         *  0                   1                   2
         *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3
         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         * | FU indicator  |   FU header   |   FU payload   ...  |
         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
         */

        /*
         *     FU Indicator
         *    0 1 2 3 4 5 6 7
         *   +-+-+-+-+-+-+-+-+
         *   |F|NRI|  Type   |
         *   +---------------+
         */

        /*
         *      FU Header
         *    0 1 2 3 4 5 6 7
         *   +-+-+-+-+-+-+-+-+
         *   |S|E|R|  Type   |
         *   +---------------+
         */

        int pktNum = frameSize / RTP_MAX_PKT_SIZE;       // 有几个完整的包
        int remainPktSize = frameSize % RTP_MAX_PKT_SIZE; // 剩余不完整包的大小
        int i, pos = 1;

        /* 发送完整的包 */
        for (i = 0; i < pktNum; i++)
        {
            rtpPacket->payload[0] = (naluType & 0x60) | 28;
            rtpPacket->payload[1] = naluType & 0x1F;
            
            if (i == 0) //第一包数据
                rtpPacket->payload[1] |= 0x80; // start
            else if (remainPktSize == 0 && i == pktNum - 1) //最后一包数据
                rtpPacket->payload[1] |= 0x40; // end

            memcpy(rtpPacket->payload+2, frame+pos, RTP_MAX_PKT_SIZE);
            ret = tcp_rtpSendPacket(socket, rtpChannel, rtpPacket, RTP_MAX_PKT_SIZE+2);
            if(ret < 0)
                return -1;

            rtpPacket->rtpHeader.seq++;
            sendBytes += ret;
            pos += RTP_MAX_PKT_SIZE;
        }

        /* 发送剩余的数据 */
        if (remainPktSize > 0)
        {
            rtpPacket->payload[0] = (naluType & 0x60) | 28;
            rtpPacket->payload[1] = naluType & 0x1F;
            rtpPacket->payload[1] |= 0x40; //end

            memcpy(rtpPacket->payload+2, frame+pos, remainPktSize+2);
            ret = tcp_rtpSendPacket(socket, rtpChannel, rtpPacket, remainPktSize+2);
            if(ret < 0)
                return -1;

            rtpPacket->rtpHeader.seq++;
            sendBytes += ret;
        }
    }

out:

    return sendBytes;
}



static int handleCmd_OPTIONS(char* result, int cseq)
{
    sprintf(result, "RTSP/1.0 200 OK\r\n"
                    "CSeq: %d\r\n"
                    "Public: OPTIONS, DESCRIBE, SETUP, PLAY\r\n"
                    "\r\n",
                    cseq);
                
    return 0;
}

static int handleCmd_DESCRIBE(char* result, int cseq, char* url)
{
    char sdp[500];
    char localIp[100];

    sscanf(url, "rtsp://%[^:]:", localIp);

    sprintf(sdp, "v=0\r\n"
                 "o=- 9%ld 1 IN IP4 %s\r\n"
                 "t=0 0\r\n"
                 "a=control:*\r\n"
                 "m=video 0 RTP/AVP 96\r\n"
                 "a=rtpmap:96 H264/90000\r\n"
                 "a=control:track0\r\n",
                 time(NULL), localIp);
    
    sprintf(result, "RTSP/1.0 200 OK\r\nCSeq: %d\r\n"
                    "Content-Base: %s\r\n"
                    "Content-type: application/sdp\r\n"
                    "Content-length: %d\r\n\r\n"
                    "%s",
                    cseq,
                    url,
                    strlen(sdp),
                    sdp);
    
    return 0;
}

/* udp
static int handleCmd_SETUP(char* result, int cseq, int clientRtpPort)
{
    sprintf(result, "RTSP/1.0 200 OK\r\n"
                    "CSeq: %d\r\n"
                    "Transport: RTP/AVP;unicast;client_port=%d-%d;server_port=%d-%d\r\n"
                    "Session: 66334873\r\n"
                    "\r\n",
                    cseq,
                    clientRtpPort,
                    clientRtpPort+1,
                    SERVER_RTP_PORT,
                    SERVER_RTCP_PORT);
    
    return 0;
}
*/

//tcp
static int handleCmd_SETUP(char* result, int cseq, int clientRtpPort)
{
    sprintf(result, "RTSP/1.0 200 OK\r\n"
                    "CSeq: %d\r\n"
                    "Session: 66334873;timeout=120\r\n"
                    "Transport: RTP/AVP/TCP;unicast;interleaved=0-1\r\n"
                    "\r\n",
                    cseq);
    
    return 0;
}

static int handleCmd_PLAY(char* result, int cseq)
{
    sprintf(result, "RTSP/1.0 200 OK\r\n"
                    "CSeq: %d\r\n"
                    "Range: npt=0.000-\r\n"
                    "Session: 66334873; timeout=0\r\n\r\n",
                    cseq);
    
    return 0;
}

//static void doClient(int clientSockfd, const char* clientIP, int clientPort,
//                        int serverRtpSockfd, int serverRtcpSockfd)
static void doClient(RTSP_buffer *prtspbuffer)
{
    char method[40];
    char url[100];
    char version[40];
    int cseq;
    int clientRtpPort, clientRtcpPort;
    char *bufPtr;
    char *pcseq;
    char* rBuf = malloc(BUF_MAX_SIZE);
    char* sBuf = malloc(BUF_MAX_SIZE);
    char line[400];
    char* pStr;
    

    while(1)
    {
        int recvLen;

        recvLen = recv(prtspbuffer->fd, prtspbuffer->in_buffer, RTSP_BUFFERSIZE, 0);
        if(recvLen <= 0)
            goto out;

        prtspbuffer->in_buffer[recvLen] = '\0';
        printf("---------------C->S--------------\n");
        printf("%s", prtspbuffer->in_buffer);

        /* 解析方法 */
        bufPtr = getLineFromBuf(prtspbuffer->in_buffer, line);
        if(sscanf(line, "%s %s %s\r\n", method, url, version) != 3)
        {
            printf("parse err\n");
            goto out;
        }

        /* 解析序列号 */
        //ffplay的CSeq出现在第三行，因此会产生错误
        //加一个pcseq，找到CSeq出现的位置。
        if ((pcseq = strstr(prtspbuffer->in_buffer, "CSeq")) == NULL) {
		     printf("can not find CSeq\n");
		     goto out;
	    }else {
		    if(sscanf(pcseq, "CSeq: %d\r\n", &cseq) != 1){
			    printf("parse err\n");
                goto out;
		    }
	    }

        /* 如果是SETUP，那么就再解析client_port */
        //这里用switch case可能会好点？
        if(!strcmp(method, "SETUP"))
        {
            while(1)
            {
                bufPtr = getLineFromBuf(bufPtr, line);
                if(!strncmp(line, "Transport:", strlen("Transport:")))
                {
                    if( (pStr = strstr(line, "client_port")) )
				    {
					    pStr = strstr(line, "=");
					    if(sscanf(pStr + 1, "%d", &clientRtpPort) != 1)
					    {
					        printf("parse client rtp port err\n");
					        goto out;
					    }
					    pStr = strstr(line, "-");
					    if((sscanf(pStr + 1, "%d", &clientRtcpPort)) != 1)
					    {
					        printf("parse client rtcp port err\n");
					        goto out;
					    }
					    prtspbuffer->prtptransport->clientRtpPort = clientRtpPort;
				    }
                    break;
                }
            }
        }

        if(!strcmp(method, "OPTIONS"))
        {
            if(handleCmd_OPTIONS(sBuf, cseq))
            {
                printf("failed to handle options\n");
                goto out;
            }
        }
        else if(!strcmp(method, "DESCRIBE"))
        {
            if(handleCmd_DESCRIBE(sBuf, cseq, url))
            {
                printf("failed to handle describe\n");
                goto out;
            }
        }
        else if(!strcmp(method, "SETUP"))
        {
            if(handleCmd_SETUP(sBuf, cseq, clientRtpPort))
            {
                printf("failed to handle setup\n");
                goto out;
            }
        }
        else if(!strcmp(method, "PLAY"))
        {
            if(handleCmd_PLAY(sBuf, cseq))
            {
                printf("failed to handle play\n");
                goto out;
            }
        }
        else
        {
            goto out;
        }

        printf("---------------S->C--------------\n");
        printf("%s", sBuf);
        send(prtspbuffer->fd, sBuf, strlen(sBuf), 0);
    
        /* 开始播放，发送RTP包 */
        /*if(!strcmp(method, "PLAY"))
        {
            int frameSize, startCode;
            char* frame = malloc(500000);
            struct RtpPacket* rtpPacket = (struct RtpPacket*)malloc(500000);
            int fd = open(H264_FILE_NAME, O_RDONLY);
            assert(fd > 0);
            rtpHeaderInit(rtpPacket, 0, 0, 0, RTP_VESION, RTP_PAYLOAD_TYPE_H264, 0,
                            0, 0, 0x88923423);

            printf("start play\n");
            printf("client ip:%s\n", clientIP);
            printf("client port:%d\n", clientRtpPort);

            while (1)
            {
                frameSize = getFrameFromH264File(fd, frame, 500000);
                if(frameSize < 0)
                {
                    break;
                }

                if(startCode3(frame))
                    startCode = 3;
                else
                    startCode = 4;

                frameSize -= startCode;
                rtpSendH264Frame(serverRtpSockfd, clientIP, clientRtpPort,
                                    rtpPacket, frame+startCode, frameSize);
                rtpPacket->rtpHeader.timestamp += 90000/25;

                usleep(1000*1000/25);
            }
            free(frame);
            free(rtpPacket);
            goto out;
        }*/
        
        /*if(!strcmp(method, "PLAY"))
        {
            //rtpstatus = true;
            printf("start play\n");
            printf("client ip:%s\n", prtspbuffer->prtptransport->clientIP);
            printf("client port:%d\n", prtspbuffer->prtptransport->clientRtpPort);
        }*/
        
        if(!strcmp(method, "PLAY"))
        {
            int frameSize, startCode;
            char* frame = malloc(500000);
            struct RtpPacket* rtpPacket = (struct RtpPacket*)malloc(500000);
            int fd = open(H264_FILE_NAME, O_RDONLY);
            assert(fd > 0);
            rtpHeaderInit(rtpPacket, 0, 0, 0, RTP_VESION, RTP_PAYLOAD_TYPE_H264, 0,
                            0, 0, 0x88923423);

            printf("start play\n");
            printf("client ip:%s\n", prtspbuffer->prtptransport->clientIP);
            printf("client port:%d\n", prtspbuffer->prtptransport->clientRtpPort);

            while (1)
            {
                frameSize = getFrameFromH264File(fd, frame, 500000);
                if(frameSize < 0)
                {
                    break;
                }

                if(startCode3(frame))
                    startCode = 3;
                else
                    startCode = 4;

                frameSize -= startCode;
                //tcp_rtpSendH264Frame(clientSockfd, rtpChannel, rtpPacket, frame+startCode, frameSize);
                tcp_rtpSendH264Frame(prtspbuffer->fd, 0, rtpPacket, frame+startCode, frameSize);
                rtpPacket->rtpHeader.timestamp += 90000/25;

                usleep(1000*1000/25);
            }
            free(frame);
            free(rtpPacket);
            goto out;
        }
        
    }
out:
    close(prtspbuffer->fd);
    free(rBuf);
    free(sBuf);
}

void *rtpserver(void *arg)
{
    RTSP_buffer *prtspbuffer = (RTSP_buffer*)arg;
    int frameSize, startCode;
    char* frame = malloc(500000);
    struct RtpPacket* rtpPacket = (struct RtpPacket*)malloc(500000);
    int fd = open(H264_FILE_NAME, O_RDONLY);
    assert(fd > 0);
    rtpHeaderInit(rtpPacket, 0, 0, 0, RTP_VESION, RTP_PAYLOAD_TYPE_H264, 0,
                            0, 0, 0x88923423);

    while (1)
    {
        if(rtpstatus)
        {
            frameSize = getFrameFromH264File(fd, frame, 500000);
            if(frameSize < 0)
            {
                continue;
            }

            if(startCode3(frame))
                startCode = 3;
            else
                startCode = 4;
            frameSize -= startCode;
            rtpSendH264Frame(prtspbuffer->prtptransport->serverRtpSockfd, 
                             prtspbuffer->prtptransport->clientIP, 
                             prtspbuffer->prtptransport->clientRtpPort,
                             rtpPacket, frame+startCode, frameSize);
            rtpPacket->rtpHeader.timestamp += 90000/25;
            usleep(1000*1000/25);
        }
        else
        {
            //free(frame);
            //free(rtpPacket);
        }    
    }
            
            
}

int main(int argc, char* argv[])
{
    int serverSockfd;
    int serverRtpSockfd, serverRtcpSockfd;
    int ret;
    RTSP_buffer rtspbuffer;
    rtspbuffer.bufferisset = false;
    struct sockaddr_in* pclientaddr;
    socklen_t len = sizeof(pclientaddr);
    pclientaddr = (struct sockaddr_in*)&rtspbuffer.stClientAddr;
    int clientSockfd;
    char clientIp[40];
    int clientPort;
    struct sockaddr ClientAddr;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    len = sizeof(addr);
    rtspbuffer.prtptransport = malloc(sizeof(RTP_transport));
    
    //struct ifconf ifc;

    serverSockfd = createTcpSocket();
    if(serverSockfd < 0)
    {
        printf("failed to create tcp socket\n");
        return -1;
    }
    //ret = ioctl(serverSockfd, SIOCGIFCONF, &ifc);

    ret = bindSocketAddr(serverSockfd, "0.0.0.0", SERVER_PORT);
    if(ret < 0)
    {
        printf("failed to bind addr\n");
        return -1;
    }

    ret = listen(serverSockfd, 10);
    if(ret < 0)
    {
        printf("failed to listen\n");
        return -1;
    }

    serverRtpSockfd = createUdpSocket();
    serverRtcpSockfd = createUdpSocket();
    if(serverRtpSockfd < 0 || serverRtcpSockfd < 0)
    {
        printf("failed to create udp socket\n");
        return -1;
    }

    if(bindSocketAddr(serverRtpSockfd, "0.0.0.0", SERVER_RTP_PORT) < 0 ||
        bindSocketAddr(serverRtcpSockfd, "0.0.0.0", SERVER_RTCP_PORT) < 0)
    {
        printf("failed to bind addr\n");
        return -1;
    }

    struct in_addr inaddr;
    inaddr.s_addr = get_route_if_ip();
    printf("rtsp://%s:%d\n", inet_ntoa(inaddr),SERVER_PORT);
    rtspbuffer.prtptransport->serverRtpSockfd = serverRtpSockfd;
    
    //开启rtp线程
    pthread_t thread=0;
    pthread_create(&thread,NULL,rtpserver,&rtspbuffer);

    while(1)
    {
        clientSockfd = accept(serverSockfd, (struct sockaddr *)&addr, &len);
        if(rtspbuffer.fd < 0)
        {
            printf("failed to accept client\n");
            return -1;
        }
        if(rtspbuffer.bufferisset) //已经有客户端连接
        {
            if(rtspbuffer.fd == clientSockfd) //是同一个客户端的事情
            {
            }
            else //新客户端
            {
                close(clientSockfd); //关闭
            }
        }
        else //没有客户端连接，添加
        {
            rtspbuffer.fd = clientSockfd;
            memcpy(	&rtspbuffer.stClientAddr, &addr, sizeof(addr));
            //strcpy(clientIp, inet_ntoa(pclientaddr->sin_addr));
            strcpy(rtspbuffer.prtptransport->clientIP, inet_ntoa(pclientaddr->sin_addr));
            //rtspbuffer.prtptransport->clientIP = clientIp;
            rtspbuffer.port = ntohs(pclientaddr->sin_port);
            printf("accept client;client ip:%s,client port:%d\n", clientIp, rtspbuffer.port);        
        }
        //doClient(rtspbuffer.fd, clientIp, rtspbuffer.port, serverRtpSockfd, serverRtcpSockfd);
        doClient(&rtspbuffer);
    }

    return 0;
}

